package com.suncaper.shop.controller;


import com.suncaper.shop.domain.Cart;
import com.suncaper.shop.domain.CartItem;
import com.suncaper.shop.domain.Product;
import com.suncaper.shop.service.CartService;
import com.suncaper.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.Map;

@Controller
public class CartController {
    @Autowired
    private ProductService productService;

    @Autowired
    private CartService cartService;

    @RequestMapping("/cart")
    public String cart(HttpSession session, Model model) {
        Cart cart = cartService.getCart(session);
        Collection<CartItem> cartItems = cart.getCartItems();
        cartService.addCartView(session, model, cart, cartItems);
        return "cart";
    }

    @PostMapping("/add")
    public String addToCart(@RequestParam("pid") Integer pid,
                            @RequestParam("count") Integer count,
                            HttpSession session,
                            HttpServletRequest request,
                            Model model) {
        if (count == null) {
            request.setAttribute("cartMes", "请输入正确的个数");
            return "redirect:/simpleproduct/" + pid;
        }
        System.out.println(pid + ":" + count);
        Product product = productService.findByPid(pid);
        Cart cart = cartService.addToCart(count, product, session);
        Collection<CartItem> cartItems = cart.getCartItems();
        cartService.addCartView(session, model, cart, cartItems);
        return "redirect:/cart";
    }

    //删除购物项
    @GetMapping("/cart/delete")
    @ResponseBody
    public Boolean deleteItem(@RequestParam("pid") Integer pid,
                              HttpSession session, Model model) {
        Cart cart = cartService.getCart(session);
        cart.removeFromCart(pid);
//        model.addAttribute("cart",cart);
        return true;
    }


}
